package own.stu.jobgib.playown.tools.classGraph;

import io.github.classgraph.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.nio.charset.StandardCharsets;

@Service("xx")
@Slf4j
public class ClassGraphTest {

    public static void main(String[] args) {
//        testFindGivenAnnotation();
        testFindExtensionFileOnClassPath();
    }

    public static void testFindExtensionFileOnClassPath() {
        URL pathUrl = ClassGraphTest.class.getClassLoader().getResource("");
        String path = pathUrl.toString();   // file:/Users/qim/Documents/idea-code/play-own/target/classes/
        path = pathUrl.getPath();           // /Users/qim/Documents/idea-code/play-own/target/classes/
        System.out.println(path);
        /*if(1  == 1){
            return;
        }*/
        ScanResult scan = new ClassGraph().verbose().enableAllInfo()
//                .acceptClasspathElementsContainingResourcePath(".")
//                .acceptClasspathElementsContainingResourcePath(path)
                .acceptPaths(path)
                .scan();

        ResourceList properties = scan.getResourcesWithExtension("properties");
        properties.forEachByteArrayIgnoringIOException(((resource, content) -> {
            log.info("content: {} ", new String(content, StandardCharsets.UTF_8));
        }));

        scan.close();
    }

    public static void testFindGivenAnnotation() {
        String fromPkg = "own.stu.jobgib.playown.tools.classGraph";
        String routeAnnotation = "org.springframework.stereotype.Service";

        ScanResult scan = new ClassGraph()
                .verbose()                  // Log to stderr
                .enableAllInfo()            // Scan classes, methods, fields, annotations
                .acceptPackages(fromPkg)    // Scan fromPkg and subpackages (omit to scan all packages)
                .scan();

        for (ClassInfo classInfo : scan.getClassesWithAnnotation(routeAnnotation)) {

            log.info("class: {}", classInfo.getName());
            AnnotationInfo annotationInfo = classInfo.getAnnotationInfo(routeAnnotation);
            log.info("annotation: {}", annotationInfo.getName());
            AnnotationParameterValueList parameterValues = annotationInfo.getParameterValues();
            for (AnnotationParameterValue parameterValue : parameterValues) {
                log.info("annotation - name: {} - value: {}", parameterValue.getName(), parameterValue.getValue());
            }
        }

        scan.close();
    }
}
